<?php

namespace app\api\controller;

use app\api\service\GPService;
use app\common\controller\BaseController;
use app\common\model\tang\BalanceLog;
use think\Exception;
use think\facade\Db;
use app\common\model\tang\Merchant;
use app\common\model\tang\CostType;
use app\common\model\tang\Cost;
use app\common\model\tang\ErpPush;
use app\admin\service\ProofService;
class Request extends BaseController
{
    public function cost()
    {
        $param = $this->request->param();
//        $param['merchant_sn'] = '12313';   //
//        $param['order_sn'] = '38211';   //
//        $param['contract_no'] = '4010012303160001';   //
//        $param['headList'] = [
//          [
//              'cost_id'=>'B011',
//              'cost_name'=>'111',
//              'cost_sn'=>'B011',
//              'amount'=>-123,
//              'start_time'=>'1677744663',
//              'end_time'=>'1677744663',
//              'remark'=>'测试账单'
//          ]
//        ];
        $logId = $this->pushLog(5, $param, 0);
        try {
            $costTypeModel = new CostType();
            $merchantModel = new Merchant();
            $balanceModel = new BalanceLog();
            $costModel = new Cost();
            if (empty($param['merchant_sn'])) return SendError('商户编号不能为空');
            if (empty($param['contract_no'])) return SendError('商户合同号不能为空');
            if (empty($param['order_sn'])) return SendError('订单编号不能为空');
            if (empty($param['headList'])) return SendError('费用明细不能为空');
            $merchantInfo = $merchantModel->where('code', $param['contract_no'])->find();
            if (empty($merchantInfo)) return SendError('商户不存在');
            $data = [];
            $proof = [];
            $balanceRecharge = [];
            foreach ($param['headList'] as $key => $val) {
                $where = [];
                $res = [];
                $costInfo = [];
                $costTypeInfo = $costTypeModel->where('cost_type_id', $val['cost_sn'])->find();
                if (!empty($costTypeInfo)) {
                    $where[] = ['billid', '=', $val['cost_id']];
                    $where[] = ['cost_type_id', '=', $costTypeInfo->id];
                    $where[] = ['start_time', '=', substr($val['start_time'], 0, -3)];
                    $where[] = ['merchant_id', '=', $merchantInfo->id];
                    $where[] = ['amount', '=', $val['amount']*100];
                    $where[] = ['end_time', '=', substr($val['end_time'], 0, -3)];
                    $costInfo = $costModel->where($where)->find();
                    if (empty($costInfo)) {//若费用已存在则不新增
                        $res = [];
//                    $res['start_time'] = substr( $val['start_time'],0,-3);
//                    $res['end_time'] = substr( $val['end_time'],0,-3);
                        $res['start_time'] = substr($val['start_time'], 0, -3);
                        $res['end_time'] = substr($val['end_time'], 0, -3);
                        $res['order_sn'] = OrderSn();
                        $res['real_amount'] = $val['amount']*100;
                        $res['statment_uuid'] = $param['order_sn'];
                        $res['amount'] = $val['amount']*100;
                        $res['all_amount'] = $val['amount']*100;
                        $res['pay_amount'] = 0;
                        $res['merchant_id'] = $merchantInfo->id;
                        $res['contract_code'] = $param['contract_no'];
                        $res['billid'] = $val['cost_id'];
                        $res['cost_type_id'] = $costTypeInfo->id;
                        $res['pay_status'] = 0;
                        $res['remark'] = '海鼎主动推送';
                        if($val['amount']<0){
                            $proofData = [];
                            $proofData['amount'] =$val['amount'];
                            $proofData['cost_type_id'] = $costTypeInfo->id;
                            $proof[] = $proofData;
                            $balanceData= [];
                            $res['pay_amount'] = $val['amount']*100;
                            $res['pay_status'] = 1;
                            $res['bill_no'] = getBill();
                            $res['pay_time'] = date('Y-m-d H:i:s');
                            $balanceData['merchant_id'] = $merchantInfo->id;
                            $balanceData['amount'] = abs($val['amount']*100);
                            $balanceData['is_top_up'] = 1;
                            $balanceData['edit'] = 1;
                            $balanceData['status'] = 1;
                            $balanceData['create_time'] = time();
                            $balanceData['update_time'] = time();
                            $balanceData['charge_time'] = time();
                            $balanceData['remark'] ='海鼎侧退款冲入余额';
//                            $balanceModel->save($balanceData);
                            $balanceRecharge[] = $balanceData;
                            $merchantModel->where('code', $param['contract_no'])->inc('balance',abs($val['amount']*100))->update();
                        }
                        $data[] = $res;
                    }
                }
            }
            $result = $costModel->saveAll($data);
            if(!empty($balanceRecharge)){
                $balanceModel->saveAll($balanceRecharge);
            }
            if(!empty($proof)){
                (new ProofService())->Balance($merchantInfo->id,$proof);
            }
            if (!empty($result)) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('推送账单成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendSuccess('推送账单失败');
            }
        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }
    }
    public function invoice(){
        $data = $this->request->param();
        if(empty($data)){
            return SendError('请传入参数');
        }
        $GPservice = new GPService();
        $result = $GPservice->doJsonServiceNew($data);
        return SendSuccess('',$result);
    }
    /**
     * 更新订单信息
     */
    public function upCost()
    {
        $param = $this->request->param();
//        $param['billId'] = 58;
//        $param['mustMoney'] = 100;
//        $param['receiveMoney'] = 58;
//        $param['returnMoney'] = 58;
//        $param['status'] = 1;
        $logId = $this->pushLog(6, $param, 0);
        try {
            if (empty($param['billId'])) return SendError('订单编号不能为空');
            if ($param['mustMoney'] < 0) return SendError('应付金额不能小于0');
            $costModel = new Cost();
            $costInfo = $costModel->where('billid', $param['billId'])->find();
            if (empty($costInfo)) return SendError('账单信息不存在');
            if ($costInfo->pay_status == 1) {
                return SendError('账单已支付');
            }
            $aomunt = bcsub($param['mustMoney'], $param['receiveMoney']);
            $costUp['real_amount'] = $aomunt;
            $costUp['amount'] = $aomunt;
            if ($param['status'] == 4) {
                $pay['pay_status'] = 1;
                $pay['pay_time'] = date('Y-m-d H:i:s', time());
                $result = $costModel->update($pay, ['billid' => $param['billId']]);
            } else {
                $result = $costModel->update($costUp, ['billid' => $param['billId']]);
            }
            if ($result) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('账单更新成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendSuccess('更新失败账单');
            }

        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }
    }

    /**
     * @return void  新增商户
     */
    public function addMerchant()
    {
        $param = $this->request->param();
//        $param['merchant_sn'] = '11111111111115';   //
//        $param['name'] = '新增的';
//        $param['company'] = 'goana';
//        $param['username'] = '浩浩';
//        $param['mobile'] = '17792486937';
//        $param['room_id'] = '23-123';
//        $param['contract_no'] = '11111111111111';
        $logId = $this->pushLog(1, $param, 0);
        if (empty($param['merchant_sn']) || empty($param['name']) || empty($param['company']) || empty($param['username']) || empty($param['mobile'])) {
            return SendError('必填数据不能为空');
        }
        try {
            $model = new Merchant();
            $isfirst = $model->where('merchant_sn', $param['merchant_sn'])->find();
            if ($isfirst) {
                return SendError('请勿重复添加');
            }
            if (isset($param['contract_info']) && is_array($param['contract_info'])) {
                $param['contract_info'] = json_encode($param['contract_info']);
            }
            $param['password'] = md5('123456');
            $result = $model->save($param);
            if ($result) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('新增商户成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendError('新增商户失败');
            }
        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }
    }

    /**
     * 记录日志
     */
    public function pushLog($type, $param, $isSuccess = 0, $fail_resaon = '')
    {
        $push = new ErpPush();
        $push->type = $type;
        $push->text = json_encode($param);
        $push->create_time = time();
        $push->is_success = $isSuccess;
        $push->fail_resaon = $fail_resaon;
        $push->save();
        return $push->id;
    }

    /**
     * @return void  编辑商户
     */
    public function editMerchant()
    {
        $param = $this->request->param();
//        $param['merchant_sn'] = '11111111111113';
//        $param['name'] = '123123';
//        $param['contract_no'] = '11111111111111';
//        $param['contract_no2'] = '11111111111111';
        $logId = $this->pushLog(2, $param, 0);
        if (empty($param['merchant_sn'])) {
            return SendError('商户编号不能为空');
        }
        try {
            $model = new Merchant();
            $isfirst = $model->where('merchant_sn', $param['merchant_sn'])->find();
            if (empty($isfirst)) {
                return SendError('商户不存在');
            }
            if (isset($param['contract_info']) && is_array($param['contract_info'])) {
                $param['contract_info'] = json_encode($param['contract_info']);
            }
//            unset($param['appId']);
//            unset($param['timestamp']);
//            unset($param['sign']);
            $result = $model->update($param, ['id' => $isfirst['id']]);
            if ($result) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('编辑成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendError('编辑失败');
            }
        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }

    }

    /**
     * 新增费用项
     */
    public function costTypeAdd()
    {
        $param = $this->request->param();
        $logId = $this->pushLog(3, $param, 0);
//        $param['cost_name'] = '水费';//收费名称
//        $param['cost_sn'] = '10001';//收费科目编号
//        $param['cost_money'] = '5';//科目单价
//        $param['tax_rate'] = '5';//税率
//        $param['tax_sn'] = '水费啊';//税率科目
//        $param['cost_type_id'] = 15;//ERP系统生成的费用项id
//        $param['tax_name'] = '水费税率';//税率名称
        if (empty($param['cost_type_id'])) return SendError('ERP系统费用项ID不能为空');
        if (empty($param['cost_name'])) return SendError('收费科目名称cost_name不能为空');
//        if (empty($param['cost_sn'])) return SendError('收费科目编号cost_sn不能为空');
        try {
            $model = new CostType();
            $isfirst = $model->where(['cost_type_id' => $param['cost_type_id']])->find();
            if ($isfirst) {
                return SendError('费用项已存在');
            }
            $result = $model->save($param);
            if ($result) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('新增费用项成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendError('新增费用项失败');
            }
        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }
    }

    /**
     * 编辑费用项
     */
    public function costTypeEdit()
    {
        $param = $this->request->param();
//        $param['cost_type_id'] = 15;//ERP系统生成的费用项id
//        $param['tax_sn'] = '水费啊啊啊啊';//税率科目
        $logId = $this->pushLog(4, $param, 0);
        if (empty($param['cost_type_id'])) {
            return SendError('ERP系统费用项ID不能为空');
        }
        try {
            $model = new CostType();
            $isfirst = $model->where('cost_type_id', $param['cost_type_id'])->find();
            if (empty($isfirst)) {
                return SendError('费用项不存在');
            }
            $result = $model->update($param, ['id' => $isfirst['id']]);
            if ($result) {
                ErpPush::update(['is_success' => 1], ['id' => $logId]);
                return SendSuccess('编辑成功', [], 200);
            } else {
                ErpPush::update(['is_success' => 0], ['id' => $logId]);
                return SendError('编辑失败');
            }
        } catch (\Exception $exception) {
            ErpPush::update(['is_success' => 0, 'fail_resaon' => $exception->getMessage()], ['id' => $logId]);
            return SendError("数据有误{$exception->getMessage()}");
        }

    }
}